/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package filters;

import beans.LoginBean;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * Filters traffic to secure pages.
 *
 * @author jonas
 */
public class LoginFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest)request;
        HttpServletResponse httpResp = (HttpServletResponse)response;

        //Pass through if a user exists in the session or some of the allows pages are accessed
        boolean passThrough = false;
        HttpSession session = httpReq.getSession();
        LoginBean lb = (LoginBean)session.getAttribute(LoginBean.MANGED_BEAN_NAME);
        if(lb != null){
            passThrough = lb.getUserLoggedIn();
        }
        else{
            System.out.println("Login bean not found!");
        }

        if(passThrough){
            chain.doFilter(request, response);
        }
        else{
            httpResp.sendRedirect("/StudentPortal/login.jspx?noLogin=1");
            //request.getRequestDispatcher("/login.jspx?noLogin=1").forward(request, response);
        }
    }

    public void destroy() {
    }
}
